import sha256 from "js-sha256"
import QRCode from "qrcodejs2";
import { printed } from "./config";

export class utils {
    constructor() {

    }

    setJsonObj(key, info) {
        localStorage.setItem(key, JSON.stringify(info));
    }

    getJsonObj(key) {
        return JSON.parse(localStorage.getItem(key));
    }

    setValue(key, value) {
        localStorage.setItem(key, value);
    }

    getValue(key) {
        return localStorage.getItem(key);
    }

    removeValue(key) {
        return localStorage.removeItem(key);
    }

    encryption(str) {
        return sha256(str)
    }

    localSubstring(str, index, length) {
        if (str.length > length) {
            return str.substring(index, length) + "...";
        }
        return str;
    }

    log(_target, msg) {
        if (printed) {
            console.log(_target, msg);
        }
    }

    // 未用
    getLocalImageUrl(node) {
        var imgURL = "";
        try {
            var file = null;
            if (node.files && node.files[0]) {
                file = node.files[0];
            } else if (node.files && node.files.item(0)) {
                file = node.files.item(0);
            }
            //Firefox 因安全性问题已无法直接通过input[file].value 获取完整的文件路径  
            try {
                imgURL = file.getAsDataURL();
            } catch (e) {
                imgURL = window.URL.createObjectURL(file);
            }
        } catch (e) {
            if (node.files && node.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    imgURL = e.target.result;
                };
                reader.readAsDataURL(node.files[0]);
            }
        }
        return imgURL;
    }

    getLocation(callback) {
        // var options = {
        //   // 获取精确位置
        //   enableHighAccuracy: false,
        //   // 超时时间
        //   timeout: 5000,
        //   maximumAge: 0,
        // };
        if (!navigator.geolocation) {
            console.log("无法获取位置信息!");
            return;
        }

        navigator.geolocation.getCurrentPosition(
            (pos) => {
                callback(pos.coords);
                // crd = { lat: pos.coords.latitude, lon: pos.coords.longitude };
                // this.lat = crd.latitude;
                // this.lng = crd.longitude;
                // console.log("Your current position is:");
                // console.log(`Latitude : ${crd.latitude}`);
                // console.log(`Longitude: ${crd.longitude}`);
                // console.log(`More or less ${crd.accuracy} meters.`);
            },
            (err) => {
                console.warn(`ERROR(${err.code}): ${err.message}`);
            },
            {
                // 获取精确位置
                enableHighAccuracy: true,
                // 超时时间
                timeout: 50000,
                maximumAge: 0,
            }
        );
    }

    generateQrcode(containerElement, text) {
        new QRCode(containerElement, {
            width: 150,
            // 高度
            height: 150,
            //要生成二维码的链接（或当前页面地址）
            text: text,
            colorDark: "#000",
            colorLight: "#fff",
        });
    }

    stringFomat() {
        var s = arguments[0];
        for (var i = 0; i < arguments.length - 1; i++) {
            var reg = new RegExp("\\{" + i + "\\}", "gm");
            s = s.replace(reg, arguments[i + 1]);
        }
        return s;
    }

    preLoadImage(imageUrl) {
        let image = new Image()
        image.src = imageUrl
        // https://www.w3school.com.cn/jsref/dom_obj_image.asp
        // let percentNum = 0;
        // image.onload = () => {
        //   this.count++
        //   // 计算图片加载的百分数，绑定到percent变量
        //   percentNum = Math.floor(this.count / 14 * 100)
        //   this.percent = `${percentNum}%`
        // }
        return image;
    }

    getRandomString() {
        // https://zhuanlan.zhihu.com/p/148173979
        var temp_url = URL.createObjectURL(new Blob());
        var uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
        URL.revokeObjectURL(temp_url);
        return uuid.substr(uuid.lastIndexOf("/") + 1);
    }

    randomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var str = '';
        for (var i = 0; i < len; i++) {
            str += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return str;
    }

    isEmpty(obj) {
        return typeof obj == "undefined" || obj == null || obj == "";
    }

    toShortTime(dataL) {
        var dateType = new Date(dataL);
        //获取年份
        var yearNum = dateType.getFullYear();
        //获取月份
        var monthNum = dateType.getMonth() + 1;
        //获取日期
        var dayNum = dateType.getDate();
        return this.stringFomat("{0}-{1}-{2}", yearNum, monthNum, dayNum);
    }

    getQueryVariable(url) {
        if (/^.*aid=(.*)$/.test(url)) {
            return RegExp.$1;
        } else {
            return null;
        }

    }

    /**
     * 
     * @param {*} fmt 
     * @param {*} date 
     */
    dateFtt(fmt, dateTime) {
        let date = new Date(dateTime);
        // console.log(date)
        // let date = this.convertUTCToLocalTime(new Date(dateTime));
        // console.log(dateTime, date)
        var o = {
            "M+": date.getMonth() + 1,     //月份 
            "d+": date.getDate(),     //日 
            "h+": date.getHours() + 8,     //小时 
            "m+": date.getMinutes(),     //分 
            "s+": date.getSeconds(),     //秒 
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds()    //毫秒 
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }

        return fmt;
    }

    convertUTCToLocalTime(dt) {
        var timeOffsetInHours = (new Date().getTimezoneOffset() / 60) + -10;
        dt.setHours(dt.getHours() + timeOffsetInHours);
        return dt;
    }

    trim(str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    }

    compare(src, target) {
        let srcLen = src.length, tarLen = target.length, start = 0, end = 0, srcArr = src.split(''), targetArr = target.split('');
        for (start = 0; start < tarLen; start++) {
            // console.log(start, targetArr[start], srcArr[start]);
            if (targetArr[start] != srcArr[start]) {
                break;
            }
        }
        for (end = tarLen; end > 0; end--) {
            if (targetArr[end] != srcArr[srcLen - (tarLen - end)]) {
                break;
            }
        }
        // console.log(target, start, end);
        return target.substring(start, end + 1);
    }

    getKeys(src) {
        // let reg = /\p{Unified_Ideograph}/u;
        if (!src) return '';
        let r = src.match("^[\u4E00-\u9FA5A-Za-z0-9]+$");
        return r ? r[0] : '';
    }

    myTrim(x) {
        return x.replace(/^\s+|\s+$/gm, '');
    }
}

export default {
    install(Vue) {
        Vue.prototype.$utils = new utils();
    }
}